#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2019-12-18 09:04:03
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：
import functools
import gc
import logging
import os
import sys
import time
import traceback
from ctypes import windll
from inspect import signature

import psutil
import win32clipboard as w
import win32con

log = logging.getLogger(name = 'main.tools')


def getText():  # 读取剪切板
    w.OpenClipboard()
    d = w.GetClipboardData(win32con.CF_TEXT)
    w.CloseClipboard()
    return d


def setText(aString):  # 写入剪切板
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardText(aString)
    w.CloseClipboard()


def Set_Message(msg, title = '警告'):
    result = windll.user32.MessageBoxA(0, msg.encode('gbk'), title.encode('gbk'), 1 | win32con.MB_ICONWARNING)
    return True if result == 1 else False

set_message =Set_Message
setMessage=Set_Message

def quit(second = 30):
    log.info("即将退出程序。。。")
    for i in range(second, 0, -1):
        log.debug("倒计时：{}".format(i))
        time.sleep(1)
    log.info("退出程序。。。")
    os._exit(0)


# 重启程序
def reset(second = 30):
    log.info("即将重启程序。。。")
    for i in range(second, 0, -1):
        log.debug("倒计时：{}".format(i))
        time.sleep(1)
    log.info("重启程序。。。")
    python = sys.executable
    os.execl(python, python, *sys.argv)


class obj(object):
    """docstring for obj"""

    def __init__(self, **kwargs):
        self.__dict__ = kwargs


# 查询函数参数
def query_func(func):
    try:
        f = signature(func)
        for name, param in f.parameters.items():
            print('参数类型:%s, 参数名:%s, 参数默认值:%s' % (param.kind, name, param.default))
    except Exception as e:
        print("函数：{},不是一个自定义函数，或内置函数，无法查询参数信息，请使用help,异常：{}".format(func.__name__, e))

# 类方法异常装饰器
def run_time(func):
    begin_time =time.clock()
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        if args:
            res = func(self, *args, **kwargs)
        else:
            res = func(self)
        return res
    log.info("运行耗时：{}秒".format(time.clock() - begin_time))
    return wrapper


# 类方法异常装饰器
def try_error_class(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            if args:
                res = func(self, *args, **kwargs)
            else:
                res = func(self)
            return res
        except Exception as e:
            log.error("异常：{}\n跟踪捕获：\n{}".format(e, traceback.format_exc()))

    return wrapper


# 普通函数装饰器
def try_error(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            return res
        except Exception as e:
            log.error("异常：{}\n跟踪捕获：\n{}".format(e, traceback.format_exc()))

    return wrapper


# 检测CPU
class check_cpu_memory(object):
    """docstring for check_cpu_memory"""

    def __init__(self):
        super(check_cpu_memory, self).__init__()
        self.cpu_count = psutil.cpu_count(logical = True)
        # 核心数
        self.process = psutil.Process(os.getpid())
        # 进程

    # 运行
    def run(self):
        cpu_count = self.process.cpu_percent(interval = 3)
        # 得到进程CPU占用
        cpu = cpu_count / self.cpu_count
        # 内存占用率
        memory = self.process.memory_percent()
        if cpu >= 30 or memory >= 30:
            log.info("程序运行，CPU占用率：%{}，或内存占用率：%{} 超过30%，10秒后即将退出程序！！！".format(cpu, memory))
            for i in range(10):
                time.sleep(1)
                log.info("倒计时：{}秒".format(9 - i))
            quit()
        else:
            log.info("程序运行，CPU占用率：%{}，或内存占用率：%{} ".format(cpu, memory))
        del cpu_count, cpu, memory
        gc.collect()

    ##进度条
# def bar(iterable=None):
#     desc='进度'
#     bar_format='{l_bar}{bar}当前/最大:[{n_fmt}-{total_fmt}] 已用/剩余:[{elapsed_s:.2f}<{remaining_s:.2f}]'
#     return tqdm.tqdm(iterable,desc=desc,bar_format=bar_format)
# if __name__ == '__main__':
#     # x=Set_Message('xxx')
#     # print(win32con.MB_ICONWARNING,x)
#     print(dir(tqdm.tqdm))

#     for i in bar(range(50)):
#         time.sleep(0.01)
#